//
//  KKPhotosManager.m
//  KKPhotosKitDemo
//
//  Created by liaozhenming on 2017/8/30.
//  Copyright © 2017年 liaozhenming. All rights reserved.
//

#import "KKPhotosManager.h"

#import "KKPhotosManager+Private.h"
#import "KKPhotosManager+Library.h"


@interface KKPhotosManager()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *kk_imagePickerController;

@property (nonatomic, assign) BOOL allowsEditing;
@property (nonatomic, assign) NSInteger imagePickerSourceType;


@property (nonatomic, assign) NSInteger imageCountSize;

@end

@implementation KKPhotosManager

+ (instancetype)kk_defaultManager {
    static KKPhotosManager *photosManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        photosManager = [[self class] new];
    });
    return photosManager;
}

#pragma mark - Private methods
- (instancetype)init {
    self = [super init];
    if (self) {
        if (KKPhotosManager_ImageRequestOptions == nil) {
            KKPhotosManager_ImageRequestOptions = [PHImageRequestOptions new];
            KKPhotosManager_ImageRequestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
            KKPhotosManager_ImageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
        }
    }
    return self;
}


- (BOOL)kk_authStatusWithCamera {
    //  获取相机权限
    __weak typeof(self) weakSelf = self;
    return [self kk_authStatusWithCamera:^{
        [weakSelf private_takePictureFromCamera];
    }];
}

- (BOOL)kk_authStatusWithLibrary {
    __weak typeof(self) weakSelf = self;
    return [self kk_authStatusWithLibrary:^{
        [weakSelf kk_takePictureFromLibraryWithCountSize: weakSelf.imageCountSize original: weakSelf.isOriginal];
    }];
}

- (void)private_takePictureFromCamera {
    //  拍照
    if (![self kk_authStatusWithCamera]) {
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        [self kk_showErrorMessage: @"设备不支持拍照功能"];
        return;
    }
    
    _kk_imagePickerController = [UIImagePickerController new];
    _kk_imagePickerController.delegate = self;
    _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    _kk_imagePickerController.allowsEditing = self.allowsEditing;
    
    [[self kk_rootViewController] presentViewController: _kk_imagePickerController animated: true completion: nil];
}

- (void)private_takePictureFromPhotoAlbum {
    //  相册
    if (![self kk_authStatusWithCamera]) {
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        [self kk_showErrorMessage: @"设备不支持相册功能"];
        return;
    }
    
    _kk_imagePickerController = [UIImagePickerController new];
    _kk_imagePickerController.delegate = self;
    _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    _kk_imagePickerController.allowsEditing = self.allowsEditing;
    
    [[self kk_rootViewController] presentViewController: _kk_imagePickerController animated: true completion: nil];
}

#pragma mark - UIImagePickerControllerDelegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage* image =  self.allowsEditing ? info[UIImagePickerControllerEditedImage] : info[UIImagePickerControllerOriginalImage];
    if (self.resultBlock && image) {
        self.resultBlock(@[image]);
    }
    [picker dismissViewControllerAnimated: true completion: nil];
}

#pragma mark - Public methods
//  选取相片 ［可从相册和拍照中获取，此时一般为单张图片］
- (void)kk_takePicture {
    [self kk_takePictureWithEdit: false];
}

//  选取相片 ［可从相册和拍照中获取，此时一般为单张图片，并且可编辑图片］
- (void)kk_takePictureWithEdit:(BOOL)edit {
    self.allowsEditing = edit;
    
    __weak typeof(self) weakSelf = self;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"选取照片" message: nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle: @"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction: cancelAction];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.imagePickerSourceType = UIImagePickerControllerSourceTypeCamera;
        [weakSelf private_takePictureFromCamera];
    }];
    [alertController addAction: action1];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle: @"相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.imagePickerSourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [weakSelf private_takePictureFromPhotoAlbum];
    }];
    [alertController addAction: action2];
    [[self kk_rootViewController] presentViewController: alertController animated: true completion: nil];
}

//  拍照选取相片，并且可支持编辑图片
- (void)kk_takePictureFromCameraWithEdit:(BOOL)edit {
    self.allowsEditing = edit;
    self.imagePickerSourceType = UIImagePickerControllerSourceTypeCamera;
    [self private_takePictureFromCamera];
}

//  相册选取相片，并且可支持编辑图片
- (void)kk_takePictureFromAlbumWithEdit:(BOOL)edit {
    self.allowsEditing = edit;
    self.imagePickerSourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self private_takePictureFromPhotoAlbum];
}

//  图库选取多张相片，小图返回
- (void)kk_takePictureFromLibraryWithCountSize:(NSInteger)size {
    [self kk_takePictureFromLibraryWithCountSize: size original: false];
}

//  图库选取多张相片。并且支持是否原图返回
- (void)kk_takePictureFromLibraryWithCountSize:(NSInteger)size original:(BOOL)original {
    
    self.imageCountSize = size;
    self.isOriginal = original;
    
    if (![self kk_authStatusWithLibrary]) {
        return;
    }
    
    [[_KKPhotosDataManger manager] setItemMaxCount: size];
    [[[_KKPhotosDataManger manager] arr_photoItems] removeAllObjects];
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    //  注册消息
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(notification_listenEvent:) name:KKPhotosManager_Event_Save_Notification object: nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(notification_listenEvent:) name:KKPhotosManager_Event_Cancel_Notification object: nil];
    
    [self kk_takePictureFromLibrary];
}

- (void)notification_listenEvent:(NSNotification*)notification {
    
    if (notification.name == KKPhotosManager_Event_Save_Notification) {
        if (self.resultBlock) {
            [KKPhotosManager kk_getImagesForAssets: [[_KKPhotosDataManger manager] arr_photoItems] original: self.isOriginal resultHandle:^(NSArray *images) {
                self.resultBlock(images);
            }];
        }
    }
}

@end
